package com.sgb.capital.view.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.view.View;

import com.google.gson.Gson;
import com.sgb.capital.R;
import com.sgb.capital.base.BaseActivity;
import com.sgb.capital.callback.Constants;
import com.sgb.capital.callback.MyZTextWatcher;
import com.sgb.capital.callback.ZMessageEvent;
import com.sgb.capital.databinding.AddtransferaccountsActivityBinding;
import com.sgb.capital.model.BusinessInfoBean;
import com.sgb.capital.utils.Utils;
import com.sgb.capital.view.pop.EnterpriseListPop;
import com.sgb.capital.view.pop.TipPop;
import com.sgb.capital.viewmodel.DealLimitModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import razerdp.basepopup.BasePopupWindow;

/**
 * 作者:张磊
 * 日期:2021/10/11 0011
 * 说明:新增转账
 */
public class AddTransferAccountsActivity extends BaseActivity {


    private AddtransferaccountsActivityBinding mBinding;
    private DealLimitModel mModel;
    private TipPop mTipPop;
    private String mMoney;
    private EnterpriseListPop mEnterpriseListPop;
    private String mSubMerName = "";
    private boolean mIsShow;
    private boolean mIsFirst = true;
    private String mLegalName;
    private int mSwitchOn;
    private boolean isOpen= true;

    public static void start(Context context) {
        Intent intent = new Intent(context, AddTransferAccountsActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }


    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        mBinding = DataBindingUtil.setContentView(this, R.layout.addtransferaccounts_activity);
        mModel = new ViewModelProvider(this).get(DealLimitModel.class);
        mTipPop = new TipPop(this);
        mTipPop.initStr("复核人员为空，请在电脑端-业务管理-复核配置进行相关人员的配置！", null, "知道了");
        mEnterpriseListPop = new EnterpriseListPop(this);
    }

    public void initData() {
        mModel.getBusinessUserInfo(this);
        mModel.getProcessInfo(this);
    }

    public void initListener() {
        mTipPop.mTvCancel.setOnClickListener(v -> {
            mTipPop.dismiss();
            if (mTipPop.mTip.contains("变化")) {
                mIsShow = true;
                mIsFirst = true;
                mBinding.tvSelect.setTextColor(Utils.getColor(R.color.color_C0C4CC));
                mBinding.tvSelect.setText("请选择");
                mBinding.etContent.setText("");
                mBinding.etMoney.setText("");
                mBinding.llShow.setVisibility(View.GONE);
                for (BusinessInfoBean bean : mEnterpriseListPop.mDatas) {
                    bean.isSelect = false;
                }
                mEnterpriseListPop.mData = mEnterpriseListPop.mDatas.get(0);
                mEnterpriseListPop.mDatas.get(0).isSelect = true;
                mModel.getProcessInfo(this);
            }
        });
        mEnterpriseListPop.setOnDismissListener(new BasePopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (mEnterpriseListPop.mData == null) return;
                if (mEnterpriseListPop.isClick) {
                    mBinding.tvSelect.setText(mEnterpriseListPop.mData.payeeCompanyName);
                    mBinding.tvSelect.setTextColor(Utils.getColor(R.color.black));
                    mBinding.tvName.setText(mEnterpriseListPop.mData.payeeLegalName);
                    mBinding.tvInvoiceCode.setText(mEnterpriseListPop.mData.payeeCertId);
                    mBinding.tvAddress.setText(mEnterpriseListPop.mData.payeeAddress);
                    mBinding.llShow.setVisibility(View.VISIBLE);
                }
            }
        });
        mBinding.llSelect.setOnClickListener(v -> {
            if (mEnterpriseListPop.mDatas.size() == 0) {
                mModel.getBusinessInfoList(this, null);
                return;
            }
            if (mIsShow) {
                mIsShow = false;
                mEnterpriseListPop.showNewInstance(mBinding.view);
            } else {
                mEnterpriseListPop.show(mBinding.view);
            }
        });
        mBinding.ivBack.setOnClickListener(v -> finish());
        mBinding.tvBtn.setOnClickListener(v -> {
            if (mBinding.llShow.getVisibility() != View.VISIBLE) {
                mTipPop.initStr("请选择收款企业", null, "知道了");
                mTipPop.show();
            } else if (Utils.isEmpty(mBinding.etMoney.getText().toString())) {
                mTipPop.initStr("请输入转账金额", null, "知道了");
                mTipPop.show();
            } else {
                mModel.list(this);
            }
        });
        mBinding.etMoney.addTextChangedListener(new MyZTextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!s.toString().contains(".")) {
                    if (s.length() > 11) {
                        mBinding.etMoney.setText(s.subSequence(0, 11));
                        mBinding.etMoney.setSelection(s.length() - 1);
                    }
                }
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        mBinding.etMoney.setText(s);
                        mBinding.etMoney.setSelection(s.length());
                    }
                }
                if (s.toString().trim().equals(".")) {
                    s = "0" + s;
                    mBinding.etMoney.setText(s);
                    mBinding.etMoney.setSelection(2);
                }
                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        mBinding.etMoney.setText(s.subSequence(0, 1));
                        mBinding.etMoney.setSelection(1);
                        return;
                    }
                }
            }
        });
    }

    @Override
    public void initObserve() {
        mModel.mName.observe(this, s -> {
            mLegalName = s;
        });
        mModel.mProcessInfoBean.observe(this, processInfoBean -> {
            if (mIsFirst) {
                mIsFirst = false;
                mModel.getBusinessInfoByCompany(this);
                mSwitchOn = processInfoBean.switchOn;
                mBinding.tvBtn.setText(mSwitchOn == 1 ? "下一步" : "立即转账");
                return;
            }
            if (processInfoBean.switchOn != mSwitchOn) {
                mTipPop.initStr("审批流程已发生变化，请刷新页面后再操作", null, "知道了");
                mTipPop.show();
                return;
            }
            String s = mBinding.etMoney.getText().toString();
            if (s.length() == 0) {
                mTipPop.initStr(mBinding.etContent.getHint().toString(), null, "知道了");
                mTipPop.show();
                return;
            }
            boolean contains = s.contains(".");
            if (contains) {
                String[] split = s.split("\\.");
                if (split.length == 0) {
                    mMoney = s.substring(0, s.length() - 1) + ".00";
                } else {
                    if (split[1].length() == 1) {
                        mMoney = split[0] + "." + (split[1] + "0");
                    } else {
                        mMoney = s;
                    }
                }
            } else {
                mMoney = s + ".00";
            }
            BusinessInfoBean data = mEnterpriseListPop.mData;
            data.remarks = mBinding.etContent.getText().toString();
            data.transferMoney = mMoney;
            data.payerCompanyName = mSubMerName;
            if (mBinding.tvBtn.getText().toString().contains("下一步")) {
                ApprovalActivity.start(this, mLegalName, 2, new Gson().toJson(data));
            } else {
                mModel.apply(this, data);
            }
        });

        mModel.mListBean.observe(this, listBeans -> {
            if (listBeans == null || listBeans.size() == 0) {
                mTipPop.initStr("复核人员为空，请在电脑端-业务管理-复核配置进行相关人员的配置！", null, "知道了");
                mTipPop.show();
            } else {
                mModel.getProcessInfo(this);
            }
        });
        mModel.mBusinessInfoByCompanyEntity.observe(this, businessInfoByCompanyEntity ->
                {
                    mSubMerName = businessInfoByCompanyEntity.subMerName;
                }
        );
        mModel.mBusinessInfoBean.observe(this, businessInfoBeans -> {
            // TODO: 2021/11/9 0009
            if (isOpen){
                isOpen = false;
                if (businessInfoBeans == null || businessInfoBeans.size() == 0)
                    return;
                businessInfoBeans.get(0).isSelect = true;
                mEnterpriseListPop.mData = businessInfoBeans.get(0);
                mEnterpriseListPop.mDatas = businessInfoBeans;
                mEnterpriseListPop.show(mBinding.view);
            }else {
                for (BusinessInfoBean bankEntity : businessInfoBeans) {
                    bankEntity.isSelect = false;
                    mEnterpriseListPop.mSsDatas.add(bankEntity);
                }
                if (mEnterpriseListPop.mSsDatas.size() != 0) {
                    mEnterpriseListPop.mLastIndex = 0;
                    mEnterpriseListPop.mSsDatas.get(0).isSelect = true;
                    mEnterpriseListPop.mData = mEnterpriseListPop.mSsDatas.get(0);
                }
                mEnterpriseListPop.mIvNull.setVisibility(mEnterpriseListPop.mSsDatas.size() == 0 ? View.VISIBLE : View.GONE);
                mEnterpriseListPop.mAdapter.setNewInstance(mEnterpriseListPop.mSsDatas);
                mEnterpriseListPop.mAdapter.notifyDataSetChanged();
            }

        });
        mModel.mCode.observe(this, s ->
                PayDealActivity.start(this, s, false, mMoney)
        );
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Subscribe
    public void getCode(ZMessageEvent event) {
        switch (event.code) {
            case Constants
                    .EVENT_HIDE_ORDERID:
            case Constants
                    .EVENT_PAY_SUCCESS_PAY:
                finish();
                break;
            case Constants
                    .EVENT_REFRESH_SEARCH:
                String s = (String) event.data;
                List<BusinessInfoBean> ssDatas = mEnterpriseListPop.mSsDatas;
                ssDatas.clear();
                List<BusinessInfoBean> datas = mEnterpriseListPop.mDatas;
                if (Utils.isEmpty(s)) {
                    for (int i = 0; i < datas.size(); i++) {
                        if (datas.get(i).isSelect) {
                            mEnterpriseListPop.mLastIndex = i;
                        }
                    }
                    mEnterpriseListPop.mAdapter.setNewInstance(datas);
                    mEnterpriseListPop.mIvNull.setVisibility(datas.size() == 0 ? View.VISIBLE : View.GONE);
                } else {
                    mModel.getBusinessInfoList(this,s);
                }
                break;
            case Constants
                    .EVENT_REFRESH:
                mIsFirst = true;
                mBinding.tvSelect.setTextColor(Utils.getColor(R.color.color_C0C4CC));
                mBinding.tvSelect.setText("请选择");
                mBinding.etContent.setText("");
                mBinding.etMoney.setText("");
                mBinding.llShow.setVisibility(View.GONE);
                for (BusinessInfoBean bean : mEnterpriseListPop.mDatas) {
                    bean.isSelect = false;
                }
                mEnterpriseListPop.mData = mEnterpriseListPop.mDatas.get(0);
                mEnterpriseListPop.mDatas.get(0).isSelect = true;
                mModel.getProcessInfo(this);
                break;


        }
    }
}